const Service = require('egg').Service;

class CirclePostService extends Service {
    // 创建圈子帖子
    async create(postData) {
        const { ctx } = this;

        // 验证用户是否存在
        const user = await ctx.model.User.findByPk(postData.user_id);
        if (!user) {
            throw new Error('用户不存在');
        }

        // 验证圈子是否存在
        const circle = await ctx.model.Circle.findByPk(postData.circle_id);
        if (!circle) {
            throw new Error('圈子不存在');
        }

        // 验证用户是否已加入该圈子
        const userCircle = await ctx.model.UserCircle.findOne({
            where: {
                user_id: postData.user_id,
                circle_id: postData.circle_id
            }
        });
        // 处理图片字段
        if (postData.images && Array.isArray(postData.images)) {
            postData.images = postData.images.join(',');
        }
        if (!userCircle) {
            throw new Error('未加入该圈子，无法发帖');
        }

        // 创建帖子
        const post = await ctx.model.CirclePost.create({
            ...postData,
            created_at: new Date(),
            updated_at: new Date(),
        });

        // 更新圈子帖子数量
        await ctx.service.circle.updatePostCount(postData.circle_id, 1);

        return await this.getPostWithUser(post.post_id);
    }

    // 获取帖子详情（包含用户信息）
    async getPostWithUser(postId) {
        const { ctx } = this;

        const post = await ctx.model.CirclePost.findByPk(postId, {
            include: [
                {
                    model: ctx.model.User,
                    as: 'author',
                    attributes: ['user_id', 'nickname', 'avatar']
                },
                {
                    model: ctx.model.Circle,
                    as: 'circle',
                    attributes: ['circle_id', 'name', 'type']
                }
            ]
        });

        if (!post) {
            throw new Error('帖子不存在');
        }

        return post;
    }

    // 获取圈子的帖子列表（分页）
    async getCirclePosts(circleId, query) {
        const { ctx } = this;
        const { page = 1, pageSize = 10 } = query;

        // 验证圈子是否存在
        const circle = await ctx.model.Circle.findByPk(circleId);
        if (!circle) {
            throw new Error('圈子不存在');
        }

        const options = {
            where: { circle_id: circleId },
            limit: parseInt(pageSize),
            offset: (parseInt(page) - 1) * parseInt(pageSize),
            include: [
                {
                    model: ctx.model.User,
                    as: 'author',
                    attributes: ['user_id', 'nickname', 'avatar']
                }
            ],
            order: [['created_at', 'DESC']]
        };

        const { count, rows } = await ctx.model.CirclePost.findAndCountAll(options);

        return {
            list: rows,
            pagination: {
                page: parseInt(page),
                pageSize: parseInt(pageSize),
                total: count,
                totalPages: Math.ceil(count / pageSize)
            }
        };
    }

    // 获取用户在所有圈子中的帖子
    async getUserCirclePosts(userId, query) {
        const { ctx } = this;
        const { page = 1, pageSize = 10 } = query;

        // 验证用户是否存在
        const user = await ctx.model.User.findByPk(userId);
        if (!user) {
            throw new Error('用户不存在');
        }

        const options = {
            where: { user_id: userId },
            limit: parseInt(pageSize),
            offset: (parseInt(page) - 1) * parseInt(pageSize),
            include: [
                {
                    model: ctx.model.User,
                    as: 'author',
                    attributes: ['user_id', 'nickname', 'avatar']
                },
                {
                    model: ctx.model.Circle,
                    as: 'circle',
                    attributes: ['circle_id', 'name', 'type']
                }
            ],
            order: [['created_at', 'DESC']]
        };

        const { count, rows } = await ctx.model.CirclePost.findAndCountAll(options);

        return {
            list: rows,
            pagination: {
                page: parseInt(page),
                pageSize: parseInt(pageSize),
                total: count,
                totalPages: Math.ceil(count / pageSize)
            }
        };
    }

    // 更新帖子信息
    async updatePost(postId, updateData, userId) {
        const { ctx } = this;

        // 检查帖子是否存在
        const post = await ctx.model.CirclePost.findByPk(postId);
        if (!post) {
            throw new Error('帖子不存在');
        }

        // 验证权限
        if (post.user_id !== userId) {
            throw new Error('无权修改此帖子');
        }
        // 处理图片字段（如果是数组，转换为逗号分隔的字符串）
        if (updateData.images && Array.isArray(updateData.images)) {
            updateData.images = updateData.images.join(',');
        }
        // 更新帖子信息
        await post.update({
            ...updateData,
            updated_at: new Date()
        });

        return await this.getPostWithUser(postId);
    }

    // 删除帖子
    async deletePost(postId, userId) {
        const { ctx } = this;

        const post = await ctx.model.CirclePost.findByPk(postId);
        if (!post) {
            throw new Error('帖子不存在');
        }

        // 验证权限
        if (post.user_id !== userId) {
            throw new Error('无权删除此帖子');
        }

        const circleId = post.circle_id;

        await post.destroy();

        // 更新圈子帖子数量
        await ctx.service.circle.updatePostCount(circleId, -1);

        return true;
    }

    // 点赞帖子
    async likePost(postId) {
        const { ctx } = this;

        const post = await ctx.model.CirclePost.findByPk(postId);
        if (!post) {
            throw new Error('帖子不存在');
        }

        // 增加点赞数
        await post.increment('like_count');

        return await post.reload();
    }

    // 取消点赞帖子
    async unlikePost(postId) {
        const { ctx } = this;

        const post = await ctx.model.CirclePost.findByPk(postId);
        if (!post) {
            throw new Error('帖子不存在');
        }

        // 减少点赞数，确保不小于0
        if (post.like_count > 0) {
            await post.decrement('like_count');
        }

        return await post.reload();
    }

    // 获取热门圈子帖子
    async getHotCirclePosts(limit = 10) {
        const { ctx } = this;

        const posts = await ctx.model.CirclePost.findAll({
            limit: parseInt(limit),
            include: [
                {
                    model: ctx.model.User,
                    as: 'author',
                    attributes: ['user_id', 'nickname', 'avatar']
                },
                {
                    model: ctx.model.Circle,
                    as: 'circle',
                    attributes: ['circle_id', 'name', 'type']
                }
            ],
            order: [
                ['like_count', 'DESC'],
                ['created_at', 'DESC']
            ]
        });

        return posts;
    }

    // 搜索圈子帖子
    async searchCirclePosts(keyword, circleId, query) {
        const { ctx } = this;
        const { page = 1, pageSize = 10 } = query;

        const where = {
            content: { [ctx.app.Sequelize.Op.like]: `%${keyword}%` }
        };

        if (circleId) {
            where.circle_id = circleId;
        }

        const options = {
            where,
            limit: parseInt(pageSize),
            offset: (parseInt(page) - 1) * parseInt(pageSize),
            include: [
                {
                    model: ctx.model.User,
                    as: 'author',
                    attributes: ['user_id', 'nickname', 'avatar']
                },
                {
                    model: ctx.model.Circle,
                    as: 'circle',
                    attributes: ['circle_id', 'name', 'type']
                }
            ],
            order: [['created_at', 'DESC']]
        };

        const { count, rows } = await ctx.model.CirclePost.findAndCountAll(options);

        return {
            list: rows,
            pagination: {
                page: parseInt(page),
                pageSize: parseInt(pageSize),
                total: count,
                totalPages: Math.ceil(count / pageSize)
            }
        };
    }
}

module.exports = CirclePostService;